package cn.ruituo.adv9;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

public class XMLReader {
    public static void main(String[] args) {
        //dom4j解析xml
        //READ
        SAXReader reader=new SAXReader();
        //相对目录
        Document doc= null;
        try {
           doc= reader.read(new File("advance/src/cn/cn.ruituo/books.xml"));
        } catch (DocumentException e) {
            System.out.println("解析失败");
            e.printStackTrace();
            return;
        }
        Element root = doc.getRootElement();
        System.out.println(root.getName());

        //   //    /    []   @
        List<Element> book = root.selectNodes("book");//xpath
        for(Element e:book){
            //获得属性
            String id=e.attributeValue("id");
            String diff=e.attributeValue("diff");
            //String->Integer
            //int bookid=Integer.parseInt(id);
            //Element ename= (Element) e.selectNodes("name").get(0);
            //确定最多一个name子节点
            Element ename=(Element) e.selectSingleNode("name");
            String name=ename.getText();
            Element eprice= (Element) e.selectSingleNode("price");
            String price=eprice.getText();
            Element epublishi= (Element) e.selectSingleNode("publish");
            String publish=epublishi.getText();
            Element edesc= (Element) e.selectSingleNode("description");
            String  desc=edesc.getText().trim();
            System.out.printf("id=%s,diff=%s,name=%s,publish=%s,描述=%s\n",id,diff,name,publish,desc);
        }
    }
}

class Book{
    private int id,diff;
    String name,publish,desc;
    private float price;
}
